package perfume

import (
	"context"
	"strings"

	"mall/common/ctxdatax"
	"mall/common/enumx"
	"mall/common/resultx"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProposalLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProposalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProposalLogic {
	return &ProposalLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProposalLogic) Proposal(req *types.ProposalReq) (resp *types.ProposalResp, err error) {
	if req.ParentId == 0 {
		return nil, resultx.NewErrCode(resultx.ENTRY_PERFUME_ID_REQUIRED)
	}

	desc := strings.TrimSpace(req.Desc)
	if len(desc) == 0 {
		return nil, resultx.NewErrCode(resultx.ENTRY_PROPOSAL_CONTENT_REQUIRED)
	}

	userId := ctxdatax.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	res, err := l.svcCtx.UserRpc.UserInfo(l.ctx, &userclient.UserInfoReq{
		Id:       int64(userId),
		AuthType: string(enumx.ThirdPartyPlatformNameWechatMini),
	})
	if err != nil {
		return nil, err
	}

	userInfo := res.UserInfo
	_, err = l.svcCtx.BlogRpc.CreateProposal(l.ctx, &blogclient.CreateProposalReq{
		ParentId:        req.ParentId,
		AuthorId:        int64(userId),
		AuthorNickname:  userInfo.Nickname,
		AuthorAvatar:    userInfo.Avatar,
		AuthorLevel:     userInfo.Level,
		Content:         desc,
		Perfumer:        req.Perfumer,
		FragranceFamily: req.FragranceFamily,
		TopNotes:        req.TopNotes,
		HeartNotes:      req.HeartNotes,
		BaseNotes:       req.BaseNotes,
		Year:            req.Year,
	})
	if err != nil {
		return
	}

	return &types.ProposalResp{
		Status:  "ok",
		Message: "操作成功",
	}, nil
}
